package cn.northsea.interceptor;

import cn.northsea.common.Result;
import cn.northsea.utils.JwtUtils;
import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static cn.northsea.common.enums.ResultCodeEnum.*;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
        System.out.println("过滤器 doFilter...");

        // 获取请求url
        String requestURL = request.getRequestURL().toString();
        System.out.println("访问路径: "+requestURL);
        // 判断请求url中是否包含login,如果包含,说明是登录操作,放行
        if(requestURL.contains("login") || requestURL.contains("register")|| requestURL.contains("/frontIndex")|| requestURL.contains("/")){
            System.out.println("登录,注册放行");
            filterChain.doFilter(request, response);
            return;
        }
        System.out.println("不是login");
        // 获取请求头中的令牌(token),
        String Authorization = request.getHeader("Authorization");
        System.out.println("Authorization: "+Authorization);
        String jwt = "";
        if (Authorization == null || !Authorization.startsWith("Bearer ")) {
            Result error = Result.error(TOKEN_INVALID_ERROR);
            String errorJson = JSON.toJSONString(error);
            System.out.println("无效token");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(errorJson);
            return;
        }else {
            jwt = Authorization.replace("Bearer ", "");
            System.out.println("JWT: "+jwt);
        }

        if(!jwt.isEmpty()){
            // 解析token，如果解析失败，返回错误结果(未登录)
            try {
                JwtUtils.parseJwt(jwt);
                response.setHeader("authorization","Bearer "+jwt);
                System.out.println("校验成功");
            } catch (Exception e) {
                Result error = Result.error(TOKEN_CHECK_ERROR);
                String errorJson = JSON.toJSONString(error);
                System.out.println("token验证失败，请重新登录");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(errorJson);
                return;
            }
        }else{
            // 判断令牌是否存在，如果不存在，返回错误结果
            Result error = Result.error(TOKEN_INVALID_ERROR);
            String errorJson = JSON.toJSONString(error);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(errorJson);
            return;
        }


        // 放行。
        filterChain.doFilter(servletRequest,servletResponse); //放行
    }

    @Override
    public void destroy() {

    }
}
